#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:do_exam1.py
# author:王雯雯
# datetime:2024-12-7
# software: PyCharm

import socket
import threading

# 创建TCP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 服务器地址和端口
server_address = ('localhost', 6666)

# 连接服务器
client_socket.connect(server_address)

# 接收服务器发送的要求输入昵称的消息
nickname = client_socket.recv(1024).decode('utf-8')
print(nickname)

# 输入昵称并发送给服务器
my_nickname = input()
client_socket.send(my_nickname.encode('utf-8'))


# 接收服务器消息的线程函数
def receive():
    while True:
        try:
            data = client_socket.recv(1024)
            if data:
                print(data.decode('utf-8'))
            else:
                print('与服务器断开连接')
                break
        except:
            print('接收消息出现错误')
            break


# 发送消息的线程函数
def send():
    while True:
        message = input()
        if message:
            full_message = f'{my_nickname}: {message}'
            client_socket.send(full_message.encode('utf-8'))


# 创建接收消息线程和发送消息线程并启动
receive_thread = threading.Thread(target=receive)
send_thread = threading.Thread(target=send)
receive_thread.start()
send_thread.start()